package cn.boot.common;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import cn.boot.entity.SessionBean;
import util.Constant;
import util.MessageUtil;

@WebFilter(filterName = "myWebRequestFilter", urlPatterns = "/sys/*")
public class WebRequestFilter implements Filter {

	private Logger logger = Logger.getLogger(WebRequestFilter.class);

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = ((HttpServletRequest) servletRequest);
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		String _path = request.getRequestURI();
		int splitIndex = _path.lastIndexOf("/");
		String path = _path.substring(splitIndex + 1, _path.length());
		String namespace = _path.substring(0, splitIndex);
		logger.info("namespace: " + namespace);

		logger.info("**PATH**: " + path);// carrier_index.action
		if (path == null) {
			forward(request, response, "");
		}
		if (namespace.endsWith("com")) {
			chain.doFilter(request, response);
			return;
		}
		try {
			HttpSession session = request.getSession(false);
			SessionBean sb = (SessionBean) session.getAttribute(Constant.SESSION_BEAN);
			if (sb == null || sb.getUser() == null) {
				login(request, response);
				return;
			}
		} catch (Exception e) {
			login(request, response);
			return;
		}
		chain.doFilter(request, response);
		return;

	}

	private static String stringVerification(String vs) {
		if (vs != null) {
			return vs.replaceAll("[^a-zA-Z0-9_]", "");
		}
		return null;
	}

	public static void main(String[] args) {
		System.out.println(stringVerification("user_query.action"));
	}

	private void forward(HttpServletRequest request, HttpServletResponse response, String message) throws ServletException, IOException {
		String IPInfo = ((HttpServletRequest) request).getRemoteAddr();
		logger.info(IPInfo + " Access Denied!");
		MessageUtil.addMessage(request, message);
		request.getRequestDispatcher("/WEB-INF/pages/common/error.jsp").forward(request, response);
	}

	private void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String IPInfo = ((HttpServletRequest) request).getRemoteAddr();
		logger.info(IPInfo + " Access Denied.");
		request.setAttribute("message", "notlogin");
		request.getRequestDispatcher("/exit.jsp").forward(request, response);
	}

	@Override
	public void destroy() {
	}
}
